package com.jcompressor;

import java.io.Serializable;

import javax.servlet.ServletContext;

import org.apache.commons.lang.text.StrBuilder;

import com.jcompressor.assertion.AssertArgument;
import com.jcompressor.config.Configurator;

public class JcompressorContext implements Serializable {
	
	private static final long serialVersionUID = 8139971226945688185L;
	
	private static JcompressorContext JCOMPRESSOR_CONTEXT;
	private static ServletContext SERVLET_CONTEXT;
	private static Configurator CONFIGURATOR;
	
	public static final String JCOMPRESSOR_DIRECTORY_NAME = ".jcompressor";
	public static final String RESOURCES_FILE_NAME = "jcompressor-resources.xml";
	public static final String RESOURCES_DIRECTORY = "resources";
	
	public JcompressorContext(final ServletContext servletContext) {
		JcompressorContext.SERVLET_CONTEXT = servletContext;
	}
	
	public static void init(final ServletContext servletContext, final Configurator configurator) {
		AssertArgument.isNotNull(servletContext, "servletContext");
		AssertArgument.isNotNull(configurator, "configurator");
		
		JcompressorContext.JCOMPRESSOR_CONTEXT = new JcompressorContext(servletContext);
		JcompressorContext.SERVLET_CONTEXT = servletContext;
		JcompressorContext.CONFIGURATOR = configurator;
		
		configurator.configure();
	}
	
	public static JcompressorContext getInstance() {
		return JcompressorContext.JCOMPRESSOR_CONTEXT;
	}
	
	public ServletContext getServletContext() {
		return JcompressorContext.SERVLET_CONTEXT;
	}
	
	public static Configurator getConfigurator() {
		return JcompressorContext.CONFIGURATOR;
	}
	
	public static String getResourcePath() {
		final JcompressorContext jcompressorContext = JcompressorContext.getInstance();
		final StrBuilder path = new StrBuilder(System.getProperty("user.home"));
		path.append('/');
		path.append(JcompressorContext.JCOMPRESSOR_DIRECTORY_NAME);
		path.append(jcompressorContext.getServletContext().getContextPath());
		path.append('/');
		return path.toString();
	}
	
	public static String getResourceFilePath() {
		final StrBuilder path = new StrBuilder(JcompressorContext.getResourcePath());
		path.append(JcompressorContext.RESOURCES_FILE_NAME);
		return path.toString();
	}
	
	public static String getResourceFileDirectory() {
		final StrBuilder path = new StrBuilder(JcompressorContext.getResourcePath());
		path.append(JcompressorContext.RESOURCES_DIRECTORY);
		path.append('/');
		return path.toString();
	}
	
}